package com.server.rule.component.triple.simple;

import org.jdom.Element;

import com.server.rule.component.triple.Triple;
import com.server.rule.component.triple.operator.BooleanOperator;
import com.server.rule.component.triple.operator.BooleanOperatorEqual;
import com.server.rule.component.triple.operator.BooleanOperatorNonEqual;
import com.shared.rule.TypeOperator;
import com.server.rule.data.Data;
import com.server.rule.data.ExceptionTypeData;
import com.shared.rule.TypeDataRule;

public class BooleanTriple extends SimpleTriple{

	@Override
	public void generateFromXML(Element xmlElement) {
		
		labelData1 = xmlElement.getAttributeValue("label1");
		labelData2 = xmlElement.getAttributeValue("label2");
		if(xmlElement.getAttributeValue("operator").equals(TypeOperator.BOOLEAN_EQUAL.toString())) operator = new BooleanOperatorEqual();	
		if(xmlElement.getAttributeValue("operator").equals(TypeOperator.BOOLEAN_NON_EQUAL.toString())) operator = new BooleanOperatorNonEqual();		
	}

	@Override
	public Element getXMLElement() {
		Element xmlElement = new Element("Triple");
		
		xmlElement.setAttribute("type","BooleanTriple");
		xmlElement.setAttribute("label1",labelData1);
		xmlElement.setAttribute("label2",labelData2);
		xmlElement.setAttribute("operator",operator.toString());
		return xmlElement;
	}

	@Override
	public boolean match(Data data) throws ExceptionTypeData {
		if(data.get(labelData1).getTypeData()!=TypeDataRule.BOOLEAN) throw new ExceptionTypeData("Mauvais type de donnes pour "+labelData1+", Attendu:"+TypeDataRule.BOOLEAN);
		if(data.get(labelData2).getTypeData()!=TypeDataRule.BOOLEAN) throw new ExceptionTypeData("Mauvais type de donnes pour "+labelData2+", Attendu:"+TypeDataRule.BOOLEAN);
		return ((BooleanOperator) operator).compare(data.getValue(labelData1),data.getValue(labelData2));		
	}

	@Override
	public boolean equals(Triple p) {
		if(!(p instanceof BooleanTriple)) return false;
		return (labelData1.equals(((BooleanTriple) p).labelData1)) && (labelData2.equals(((BooleanTriple) p).labelData2)) && (operator.equals(((BooleanTriple) p).operator));
	}

}
